/*
 * To change this template, choose Tools | 

Templates
 * and open the template in the editor.
 */
package stdio.costa.imoca.notification.email;

import java.util.Date;
import java.util.List;
import java.util.Properties;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class EmailSender implements EmailApi, InitializingBean {

	@Value("#{properties['mail.transport.protocol']}")
	private String mailTransportProtocol;

	@Value("#{properties['mail.smtp.host']}")
	private String mailSmtpHost;

	@Value("#{properties['mail.smtp.port']}")
	private String mailSmtpPort;

	@Value("#{properties['mail.smtp.user']}")
	private String mailSmtpUser;

	@Value("#{properties['mail.smtp.password']}")
	private String mailSmtpPassword;

	@Value("#{properties['mail.smtp.auth']}")
	private String mailSmptAuth;

	private Properties emailProperties;

	@Override
	public void afterPropertiesSet() throws Exception {
		emailProperties = new Properties();
		emailProperties.setProperty("mail.transport.protocol",
				mailTransportProtocol);
		emailProperties.setProperty("mail.smtp.port", mailSmtpPort);
		emailProperties.setProperty("mail.smtp.host", mailSmtpHost);
		emailProperties.setProperty("mail.smtp.auth", mailSmptAuth);
	}

	@Override
	public void sendEmail(List<EmailRecipient> recipientList, String title,
			String content) {

		try {
			Session session = Session.getDefaultInstance(emailProperties);

			MimeMessage message = this.wrapMessage(recipientList, title,
					content, session);

			this.sendMessage(message, session);

		} catch (MessagingException e) {
			e.printStackTrace();
		}
	}

	private MimeMessage wrapMessage(List<EmailRecipient> recipientList,
			String title, String content, Session session)
			throws MessagingException {

		MimeMessage message = new MimeMessage(session);

		message.setSubject(title);

		message.setFrom(new InternetAddress(this.mailSmtpUser));

		for (EmailRecipient recipient : recipientList) {
			message.addRecipient(recipient.getRecipientType(),
					recipient.getAddress());
		}

		message.setSentDate(new Date());

		message.setText(content);

		return message;
	}

	private void sendMessage(MimeMessage message, Session session)
			throws MessagingException {

		message.saveChanges();

		Transport transport = session.getTransport();

		try {

			transport.connect(this.mailSmtpUser, this.mailSmtpPassword);

			transport.sendMessage(message, message.getAllRecipients());

		} finally {
			transport.close();
		}
	}
}
